/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package com.inspur.edp.metadata.rtcustomization.servermanager.repository;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.inspur.edp.lcm.metadata.api.entity.GspMetadata;
import com.inspur.edp.lcm.metadata.api.entity.Metadata4Ref;
import com.inspur.edp.lcm.metadata.api.entity.MetadataPackage;
import com.inspur.edp.lcm.metadata.api.entity.MetadataPackageHeader;
import com.inspur.edp.lcm.metadata.api.entity.MetadataPackageReference;
import com.inspur.edp.lcm.metadata.api.entity.MetadataPackageVersion;
import com.inspur.edp.lcm.metadata.api.entity.ProcessMode;
import com.inspur.edp.lcm.metadata.api.entity.ServiceUnitInfo;
import com.inspur.edp.lcm.metadata.common.ServiceUtils;
import com.inspur.edp.metadata.rtcustomization.api.entity.GspMdpkg;
import com.inspur.edp.metadata.rtcustomization.api.exception.ErrorCodes;
import com.inspur.edp.metadata.rtcustomization.api.exception.LcmMetadataException;
import com.inspur.edp.metadata.rtcustomization.servermanager.CustomizationServiceContext;
import com.inspur.edp.metadata.rtcustomization.servermanager.dac.GspMdpkgRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Slf4j
public class GspMdpkgRepoService {
    private final GspMdpkgRepository gspMdpkgRepo;
    private final MdRtRepoService mdRtRepoService;

    public GspMdpkgRepoService(GspMdpkgRepository gspMdpkgRepo, MdRtRepoService mdRtRepoService) {
        this.gspMdpkgRepo = gspMdpkgRepo;
        this.mdRtRepoService = mdRtRepoService;
    }

    public void save(GspMdpkg mdpkg) {
        gspMdpkgRepo.save(mdpkg);
    }

    public GspMdpkg findByName(String name) {
        return gspMdpkgRepo.findByName(name);
    }

    public void delete(GspMdpkg gspMdpkg) {
        gspMdpkgRepo.delete(gspMdpkg);
    }

    public GspMdpkg buildGspMdpkgByFileString(String fileString, MetadataPackage metadataPackage) {
        try{
            GspMdpkg gspMdpkg = findByName(metadataPackage.getHeader().getName());
            gspMdpkg = gspMdpkg == null ? new GspMdpkg(metadataPackage.getHeader().getName(), CustomizationServiceContext.getUserName()) : gspMdpkg;

            gspMdpkg.setVersion(metadataPackage.getHeader().getVersion().getVersionString());
            gspMdpkg.setLocation(metadataPackage.getHeader().getLocation());
            gspMdpkg.setProcessmode(Objects.nonNull(metadataPackage.getHeader().getProcessMode()) ? metadataPackage.getHeader().getProcessMode().name() : ProcessMode.generation.name());
            gspMdpkg.setReferenceinfo(ServiceUtils.getMapper().writeValueAsString(metadataPackage.getReference()));
            if(Objects.nonNull(metadataPackage.getServiceUnitInfo())){
                gspMdpkg.setAppcode(metadataPackage.getServiceUnitInfo().getAppCode());
                gspMdpkg.setServiceunitcode(metadataPackage.getServiceUnitInfo().getServiceUnitCode());
            }
            gspMdpkg.setLastChangedBy(CustomizationServiceContext.getUserName());
            gspMdpkg.setLastChangedOn(LocalDateTime.now());
            gspMdpkg.setManifestInfo(fileString);

            return gspMdpkg;
        }
        catch(Exception e){
            log.error(fileString);
            throw new LcmMetadataException(e, ErrorCodes.ECP_METADATA_0015);
        }
    }

    public List<GspMdpkg> findAllLastChangedOn() {
        return gspMdpkgRepo.findAllLastChangedOn();
    }

    public MetadataPackage findMetadataPackageByName(String name) {
        GspMdpkg gspMdpkg = gspMdpkgRepo.findByName(name);
        if (gspMdpkg == null) {
            return null;
        }
        List<Metadata4Ref> metadata4Refs = mdRtRepoService.findAllByMdpkgid(gspMdpkg.getId());
        return buildMetadataPackage(gspMdpkg, metadata4Refs);
    }

    public List<GspMdpkg> findAll() {
        return gspMdpkgRepo.findAll();
    }

    private MetadataPackage buildMetadataPackage(GspMdpkg gspMdpkg, List<Metadata4Ref> metadata4Refs) {
        if (gspMdpkg == null || CollectionUtils.isEmpty(metadata4Refs)) {
            return null;
        }
        MetadataPackage metadataPackage = new MetadataPackage();
        MetadataPackageHeader metadataPackageHeader = new MetadataPackageHeader();
        metadataPackageHeader.setName(gspMdpkg.getName());
        metadataPackageHeader.setVersion(new MetadataPackageVersion(gspMdpkg.getVersion()));
        metadataPackageHeader.setLocation(gspMdpkg.getLocation());
        metadataPackageHeader.setProcessMode(ProcessMode.valueOf(gspMdpkg.getProcessmode()));
        metadataPackage.setHeader(metadataPackageHeader);
        ServiceUnitInfo serviceUnitInfo = new ServiceUnitInfo();
        serviceUnitInfo.setAppCode(gspMdpkg.getAppcode());
        serviceUnitInfo.setServiceUnitCode(gspMdpkg.getServiceunitcode());
        metadataPackage.setServiceUnitInfo(serviceUnitInfo);
        List<MetadataPackageReference> references = null;
        try {
            references = ServiceUtils.getMapper().readValue(gspMdpkg.getReferenceinfo(),
                    new TypeReference<List<MetadataPackageReference>>(){});
        } catch (JsonProcessingException e) {
            log.info("反序列化元数据包的references失败：" + gspMdpkg.getName());
        }
        metadataPackage.setReference(references);
        List<GspMetadata> metadatas = new ArrayList<>();
        metadata4Refs.forEach(metadata4Ref -> metadatas.add(metadata4Ref.getMetadata()));
        metadataPackage.setMetadataList(metadatas);
        return metadataPackage;
    }

    public void makeUnique() {
        List<GspMdpkg> gspMdpkgs = gspMdpkgRepo.findAllGroupByNameHavingCountGreaterThanOne();
        if (CollectionUtils.isEmpty(gspMdpkgs)) {
            return;
        }

        List<GspMdpkg> gspMdpkgsToDelete = new ArrayList<>();
        gspMdpkgs.forEach(gspMdpkg -> {
            List<GspMdpkg> allByName = gspMdpkgRepo.findAllByNameAndLastChangedOn(gspMdpkg.getName(), gspMdpkg.getLastChangedOn());
            if (!CollectionUtils.isEmpty(allByName)) {
                gspMdpkgsToDelete.add(allByName.get(0));
            }
        });
        if (!CollectionUtils.isEmpty(gspMdpkgsToDelete)) {
            gspMdpkgRepo.deleteAll(gspMdpkgsToDelete);
        }

        // 检查是否还有重复
        makeUnique();
    }

    public List<GspMdpkg> findAllManifest() {
        return gspMdpkgRepo.findAllManifest();
    }
}
